use std::isize;
use pest::iterators::Pair;
use pest::Parser;
use pest_derive::Parser;

#[derive(Parser)]
#[grammar = "lexer.pest"]
struct ExpressionParser;

pub fn parse_file_by_lines(content: &str) {
    let file = ExpressionParser::parse(Rule::FILE, content).expect("unsuccessful parse")   // unwrap the parse result
        .next().unwrap();
    let mut success_vec = Vec::new();
    let mut fail_vec = Vec::new();
    for pair in file.into_inner() {
        for inner in pair.into_inner() {
           match process_pair(inner) {
               Ok(result) => success_vec.push(result),
               Err(e) => fail_vec.push(e),
           }
       }
    }
    if fail_vec.is_empty() {
        for inner in success_vec {
            eprintln!("{inner}")
        }
    } else {
        for inner in fail_vec {
            eprintln!("{inner}")
        }
    }
}

// 处理解析结果，将非十进制的内容转换为十进制
fn process_pair(pair: Pair<Rule>) -> Result<String, String> {
    let rule = pair.as_rule();
    let content = pair.as_str();
    // 获取行号和列号
    let (line, _) = pair.line_col();

    match rule {
        Rule::INTEGER_CONST => {
            // 尝试解析十进制数
            if let Ok(num) = content.parse::<isize>() {
                Ok(format!("INTEGER_CONST {} at Line {}.", num, line))
            } else {
                // 如果不是标准十进制格式，尝试其他进制
                match converted_to_decimal(content) {
                    Ok(numm) => Ok(format!("INTEGER_CONST {} at Line {}.", numm, line)),
                    Err(_) => Err(format!("Error type A at Line {}: '{}'", line, content)),
                }
            }
        }
        Rule::INVALID => {
            Err(format!("Error type A at Line {}: '{}'", line, content))
        }
        _ => {
            Ok(format!("{:?} {} at Line {}.", rule, content, line))
        }
    }
}

// 将非十进制内容转换为十进制
fn converted_to_decimal(content: &str) -> Result<isize, ()> {
    // 处理十六进制 (以 0x 或 0X 开头)
    if content.starts_with("0x") || content.starts_with("0X") {
        if let Ok(num) = isize::from_str_radix(&content[2..], 16) {
            return Ok(num);
        }
    }

    // 处理八进制 (以 0 开头)
    if content.starts_with("0") && content.len() > 1 {
        if let Ok(num) = isize::from_str_radix(&content[1..], 8) {
            return Ok(num);
        }
    }
    Err(())
}